$(function () {


    var query = {},
        $update = $('.btn-update'),
        $delete = $('.btn-delete'),
        $create = $('.btn-create'),
        $ups = $('.batch-up'),
        $group = $('.batch-group'),
        $log = $('.btn-log'),
        $upload = $('.btn-chongdi'),
        $banners = $('.btn-allow'),
        $plus = $('.plus'),
        $refuse = $('.btn-refuse'),
        $detail = $('.btn-dist-role'),
        // $import = $('.btn-chongdi'),
        $tpl = $('.btn-hexiao'),
        strHtml = $('#form-template').html();
    onClick($ups, function () { // 批量上架
        return window.location.href = '../../sys/category/dispatch-items.html?type1=ups';// 批量上架
    })
    onClick($group, function () { // 批量拼团
        var $current = $(this).data('json');

        if (confirm($current.status == 0 ? '确认上架?' : '确认下架')) {
            $.post('/offer/updatePlain',
                {
                    id: $current.id,
                    status: $current.status == 0 ? 1 : 0
                },
                function (res) {
                    if (res.code == 200) {
                        search({}, true)
                        fnSuccess('操作成功～')
                    } else {
                        fnFail('操作失败～')
                    }
                })
        }
        // return window.location.href = '../../sys/category/dispatch-items.html?type1=groups';//批量拼团
    })
    onClick($upload, function () { // 植物卡片上传
        var $json = $(this).data('json');
        uploadFn('植物卡', {
            w: 500,
            h: 300,
            num: 12,
            labelNum: '12 upload-custom-label',
            noCrop: false,
            preview: 'left-top-preview'
        }, function (data) {
            closeLayer(data.layerIndex);
            $.post('/offer/updatePlain', {id: $json.id, tags: data.path}, function (res) {
                if (res.code == 200) {
                    search({}, true);
                    fnSuccess('上传成功～')
                } else {
                    fnFail(res.error || '上传失败！')
                }
            })
            console.log(data);
        });
    })
    var config = {
        query: '/offer/query?productId=plant',//分页查询URL,
        query_store: '/store/query?size=' + maxSize,//分页查询URL,
        create: '/offer/create',//create,
        plus: '/offer/plus',//create,//增加可售数量
        update: '/offer/update',
        queryAccount: '/payType/query?type=2',// // 供货地账户
        'delete': '/offer/delete'
    };
    // enableBtn($tpl, {})
    // enableBtn($import, {})
    onClick($tpl, function () {
        var $current = $(this).data('json');
        window.location.href = '../../sys/category/index.html?type=days-manager&targetId=' + $current.id;
        // window.open('/admin/libs/批量上货模板.xlsx', '_blank');
    });
    // onClick($import, function () {
    //     //批量导入
    //     uploadFn('批量上货(请严格按模板字段批量上货)', {
    //         url: '/api/admin/offer/import',
    //         num: 12,
    //         labelNum: '12 upload-custom-label',
    //         plain: true,// 普通文件，非图片文件
    //         noCrop: true,
    //     }, function (data) {
    //         //if()
    //         closeLayer(data.layerIndex);
    //         console.log(data);//
    //         search({}, true);
    //         if (data.data && data.data.length) {
    //             alert('导入成功, 货号为' + _.pluck(data.data[0], 'no').join(',') + '的数据因货号重复没有被导入！')
    //         } else {
    //             alert('导入成功')
    //         }
    //     });
    //
    // });
    onClick($refuse, function () {
        var $current = $(this).data('json');
        window.location = './../info/goods-info.html?id=' + $current.id + '&type=offer&name=' + $current.name;
    });
    onClick($log, function () {
        var $current = $(this).data('json');
        window.location = './../../log/log.html?id=' + $current.id + '&type=offer';
    });

    function filterFn(item, fieldName) {
        if (!item[fieldName])return '';
        return item[fieldName].split(',').map(function (item) {
            if (!item)return '';
            return window[fieldName][item] && window[fieldName][item] && window[fieldName][item][0].name;
        }).join(',');
    }

    function search(obj, isForce) {
        gSearch({
            url: config.query,
            query: obj,
            table: true,
            isForce: isForce,
            render: function (list, opt) {
                var _$table = $('.table-responsive .table');
                if (typeof list == 'string') {
                    return _$table.html(list);
                }
                destroyBtn();
                _$table.$table($.extend(TABLE_SETTING, {
                    checkbox: true, // 是否显示复选框
                    seqNum: true, // 是否显示序号
                    sort: search, //排序回调函数
                    showSearchComplex: true,
                    destroyBtn: destroyBtn, //禁用按钮
                    createBtn: createBtn, // 启用她扭
                    toolbar: '.toolbar',
                    enableSetting: true,//允许自定义显示列
                    search: function (obj) { //搜索框查询函数
                        search(obj)
                    },
                    rendered: function () {

                        if (opt.lastSearchKey) {
                            searchInputValue(opt.lastSearchKey);
                        }

                        if (window.categoryId && !$('[name=categoryId]').data('init')) {//
                            var filterObj = lsGet(opt.lastSearchKey);
                            selectpickerFn({
                                ele: $('[name=categoryId]'),
                                name: 'categoryId',
                                label: '请选择分类',
                                placeholder: '所有分类',
                                selected: filterObj.categoryId || '',
                                list: _.flatten(_.values(window.categoryId)),
                                change: function (id) {
                                    console.log(id);
                                    $('[name=categoryId]').val(id);
                                    search({categoryId: id, page: 1}, true)
                                }
                            })
                            selectpickerFn({
                                ele: $('[name=brand]'),
                                name: 'brand',
                                label: '请选择品牌',
                                selected: filterObj.brand || '',
                                placeholder: '所有植物品牌',
                                list: _.flatten(_.values(window.brand)),
                                change: function (id) {
                                    console.log(id);
                                    search({brand: id, page: 1}, true)
                                }
                            })
                        }
                    },
                    fields: [
                        {name: 'id', label: '植物ID'},
                        {name: 'name', label: '植物名称', enableSearch: true},
                        {name: 'applyAge', label: '成长天数', enableSearch: true},
                        {
                            name: 'desc1', label: '描述', filter: function (item) {
                            return viewMore(item.desc1 || ''); // 预览更多内容
                        }
                        },
                        {name: 'varsNameIds', label: '出生地'},
                        {name: 'varsValueIds', label: '基本技能'},
                        {
                            name: 'brand', label: '品种', enableSearch: true,
                            filter: function (item) {
                                return window.brand && window.brand[item.brand] && window.brand[item.brand][0] && window.brand[item.brand][0].name;
                            }
                        },
                        {
                            enableSearch: true,
                            name: 'categoryId', label: '分类', filter: function (item) {
                            return window.categoryId && window.categoryId[item.categoryId] && window.categoryId[item.categoryId][0] && window.categoryId[item.categoryId][0].name;
                            //return window.categoryId(item, 'categoryId');
                        }
                        },
                        {
                            name: 'thumbnail', label: '缩略图',
                            filter: function (item) {
                                if (item.thumbnail) {
                                    return '<a target="_blank" href="' + item.thumbnail + '" title="点击预览"><img style="height:60px;border-radius:5px;" src="' + item.thumbnail + '" /></a>'
                                } else {
                                    return getDefaultImgStr();
                                }
                            }
                        },
                        {
                            name: 'online', label: '状态',
                            filter: function (item) {
                                return item.status == '1' ? '<span class="label label-success">上架</span>' : '<span class="label label-warning">下架</span>';
                            }
                        },
                        {
                            name: 'tags', label: '视频', filter: function (item) {
                            if (item.refundNotice) {
                                return '<a target="_blank" href="' + item.refundNotice + '" title="视频">' +
                                    (!!item.deliveryNotice ? '<img style="height:60px;border-radius:5px;" src="' + item.deliveryNotice + '" />' : (getDefaultImgStr()) ) +
                                    '</a>'
                            } else {
                                return getDefaultImgStr();
                            }
                        }
                        },
                        {
                            name: 'tags', label: '视频缩略图', filter: function (item) {
                            if (item.deliveryNotice) {
                                return '<a target="_blank" href="' + item.deliveryNotice + '" title="视频"><img style="height:60px;border-radius:5px;" src="' + item.deliveryNotice + '" /></a>'
                            } else {
                                return getDefaultImgStr();
                            }
                        }
                        },
                        {
                            name: 'tags', label: '植物卡', filter: function (item) {
                            if (item.tags) {
                                return '<a target="_blank" href="' + item.tags + '" title="点击预览"><img style="height:60px;border-radius:5px;" src="' + item.tags + '" /></a>'
                            } else {
                                return getDefaultImgStr();
                            }
                        }
                        },
                        {
                            name: 'tags', label: '二维码', filter: function (item) {
                            return '<a target="_blank" href="/api/getQrcode?url=' + item.id + '">查看二维码</a>'
                        }
                        },
                    ],
                    data: list || [],
                }));
            }
        }, false);
    }

    function getGoods(item, isUpdate) {
    }

    onClick($update, function () {
        var $current = $(this).data('json'), self = this;//
        return window.location.href = './edit.html?id=' + $current.id;
    });
    onClick($create, function () {//
        return window.location.href = './edit.html';//
    });

    onClick($delete, function () {
        var $current = $(this).data('json'), self = this;
        $(self).button('loading');
        if (confirm('确认删除"' + $(this).data('json').name + '"?')) {
            $.post(config['delete'], {id: $current.id}, function (xhr, data) {
                $(self).button('reset');
                if (xhr.code == 200) {
                    fnSuccess('删除成功!');
                    $('tr[id=' + $current.id + ']').remove();
                    // $(self).closest('tr').remove();
                    setTimeout(function () {
                        destroyBtn();
                    }, 0)
                } else {
                    alert('删除失败：' + xhr.error);
                }
            })
        } else {
            $(self).button('reset');
        }
    });
    $.when(
        $.get('/category/list?type1=plant-cateogry&level=1&size=1000'),
        $.get('/category/list?type1=plant-variety&size=1000')
    )
        .then(function (category, brand) {
            search({}, true);
            brand = brand[0].list;
            category = category[0].list;
            window.brand = _.groupBy(brand, 'id');
            window.categoryId = _.groupBy(category, 'id');
        })

    function destroyBtn() {
        $update.data('json', null);
        $delete.data('json', null);
        disableBtn($update);
        disableBtn($plus);
        disableBtn($log);
        disableBtn($delete);
        disableBtn($upload);
        disableBtn($refuse);
        disableBtn($tpl);
        disableBtn($banners);
        disableBtn($group);
        disableBtn($detail);
    }

    function createBtn(_this) {
        destroyBtn();
        var item = $(_this).data('json');
        enableBtn($tpl, item);
        enableBtn($update, item);
        enableBtn($log, (item));
        enableBtn($plus, (item));
        enableBtn($group, (item));
        if (item.status == 0) {
            enableBtn($delete, item);
        }

        enableBtn($upload, item);
        enableBtn($refuse, item);
        enableBtn($banners, item);
        enableBtn($detail, item);
    }

    function validate(modal, obj) {
        console.log('000')
        $('#registrationForm')
            .find('[name="color"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('color');
            })
            .end()
            .find('[name="sizeId"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('sizeId');
            })
            .end()
            .find('[name="applyAge"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('applyAge');
            })
            .end()
            .find('[name="season"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('season');
            })
            .end()
            .find('[name="categoryId"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('categoryId');
            })
            .end()
            .find('[name="discountId"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('discountId');
            })
            .end()
            .find('[name="deliverPlace"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('deliverPlace');
            })
            .end()
            .find('[name="brand"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('brand');
            })
            .end();
        // obj.color && $('[name="color"]').selectpicker('val', obj.color.split(','));
        // obj.season && $('[name="season"]').selectpicker('val', obj.season.split(','));
        obj.categoryId && $('[name="categoryId"]').selectpicker('val', obj.categoryId.split(','));
        obj.discountId && $('[name="discountId"]').selectpicker('val', obj.discountId.split(','));
        // obj.brand && $('[name="brand"]').selectpicker('val', obj.brand.split(','));

        $('#registrationForm').formValidation('destroy')
            .formValidation($.extend({}, VALIDATION_SETTING, {
                fields: {
                    name: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '报价名称必填'
                            },
                            stringLength: {
                                min: 3,
                                max: 40,
                                message: '报价名称长度最少3位，最多40位'
                            }
                        }
                    },

                    price: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '货物单价必填'
                            },
                            greaterThan: {
                                value: 0,
                                message: '单价必须大于0'
                            },
                            // numeric: {
                            //     message: '单价必须是数字',
                            // }
                        }
                    },
                    priceUnit: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '价格单位必填'
                            },
                        }
                    },
                    unit: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '计量单位必填'
                            },
                        }
                    },
                    qualitySpec: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '品质规格必填'
                            },
                        }
                    },
                    packSpec: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '包装规格必填'
                            },
                        }
                    },

                    qualityRequire: {
                        row: '.col-xs-7',
                        validators: {
                            notEmpty: {
                                message: '质量标准必选'
                            },
                        }
                    },
                    salesMan: {
                        row: '.col-sm-6',
                        validators: {
                            notEmpty: {
                                message: '销售员佣金必填'
                            },
                        }
                    },
                    salesManager: {
                        row: '.col-sm-6',
                        validators: {
                            notEmpty: {
                                message: '销售经理佣金必填'
                            },
                        }
                    },
                }
            }))
            .off('success.form.fv')
            .on('success.form.fv', function (e) {
                e.preventDefault();
                var form = parseSearch($(e.target).serialize());
                var url = '';
                if (form.id) { // is update?
                    url = config.update;
                } else {
                    url = config.create;
                    delete form.id;
                }
                if (form.name) {
                    form.name = form.name.trim();
                }

                if (form.priceUnit) {
                    form.priceUnit = form.priceUnit.replace('%2F', '/')
                }
                form.actualPrice = form.price;

                if (!!form.color) {
                    form.color = [',', form.color, ','].join('')
                }
                if (!!form.season) {
                    form.season = [',', form.season, ','].join('')
                }
                if (!!form.sizeId) {
                    form.sizeId = [',', form.sizeId, ','].join('')
                }
                if (!!form.applyAge) {
                    form.applyAge = [',', form.applyAge, ','].join('')
                }
                if (!!form.categoryId) {
                    form.categoryId = [',', form.categoryId, ','].join('')
                }
                form.salesManager = 0;
                $.post(url, form, function (xhr, data) {
                    if (xhr.code == 200) {
                        fnSuccess(form.id ? '保存成功' : '创建成功!');
                        search({}, true);
                        window.$index && closeLayer(window.$index);
                    } else {
                        alert(xhr.error || xhr.msg);
                    }
                });
            });
    }
});